package com.ruoyi.bill.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.bill.domain.BillCustomInvest;
import com.ruoyi.bill.domain.BillFinancePort;
import com.ruoyi.bill.domain.BillPort;
import com.ruoyi.bill.domain.bo.BillCustomInvestBo;
import com.ruoyi.bill.domain.vo.BillCustomInvestVo;
import com.ruoyi.bill.domain.vo.BillFinancePortVo;
import com.ruoyi.bill.domain.vo.BillPortVo;
import com.ruoyi.bill.mapper.BillBankCusMapper;
import com.ruoyi.bill.mapper.BillCustomInvestMapper;
import com.ruoyi.bill.service.IBillCustomInvestService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.bill.domain.bo.BillFinanceBo;
import com.ruoyi.bill.domain.vo.BillFinanceVo;
import com.ruoyi.bill.domain.BillFinance;
import com.ruoyi.bill.mapper.BillFinanceMapper;
import com.ruoyi.bill.service.IBillFinanceService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户财务台账Service业务层处理
 *
 * @author linziheng
 * @date 2024-02-29
 */
@RequiredArgsConstructor
@Service
public class BillFinanceServiceImpl implements IBillFinanceService {

    private final BillFinanceMapper baseMapper;
    private final BillCustomInvestMapper billCustomInvestMapper;
    private final IBillCustomInvestService iBillCustomInvestService;
    private final BillBankCusMapper billBankCusMapper;

    @Override
    public R matching(){
        List<BillFinanceVo> billFinances = baseMapper.queryListToday();
        List<BillCustomInvestVo> billCustomInvests =  billCustomInvestMapper.queryListToday();
        if(billFinances.isEmpty() || billCustomInvests.isEmpty()){
            return R.fail("未查到需要匹配的数据");
        }
        billCustomInvests = billCustomInvests.stream().filter(billCustomInvestVo->billCustomInvestVo.getAccountTime()!=null).collect(Collectors.toList());
        Map<String, Double> billFinancesMap = billFinances.stream().collect(Collectors.groupingBy(BillFinanceVo::getTemp,Collectors.summingDouble(BillFinanceVo::getDoubleNum)));
        Map<String, Double> billCustomInvestsMap = billCustomInvests.stream().collect(Collectors.groupingBy(BillCustomInvestVo::getTemp,Collectors.summingDouble(BillCustomInvestVo::getDoubleNum)));

        for (String key : billFinancesMap.keySet()) {
            Double value = billFinancesMap.get(key);
            if(Objects.equals(value, billCustomInvestsMap.get(key))){
                //匹配成功
                baseMapper.update(null,
                    new LambdaUpdateWrapper<BillFinance>()
                        .eq(BillFinance::getHtName, key.split("@")[0])
                        .eq(BillFinance::getPaymentDate, key.split("@")[1])
                        .set(BillFinance::getCheckType, "0"));
                billCustomInvestMapper.update(null,
                    new LambdaUpdateWrapper<BillCustomInvest>()
                        .eq(BillCustomInvest::getHtName,key.split("@")[0])
                        .eq(BillCustomInvest::getAccountTime,key.split("@")[1])
                        .set(BillCustomInvest::getFinanceType, "0"));
            }
        }
        return R.ok("数据已进行匹配");
    }
    /**
     * 查询客户财务台账
     */
    @Override
    public BillFinanceVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询客户财务台账列表
     */
    @Override
    public TableDataInfo<BillFinanceVo> queryPageList(BillFinanceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BillFinance> lqw = buildQueryWrapper(bo);
        Page<BillFinanceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        TableDataInfo<BillFinanceVo> res = TableDataInfo.build(result);
        res.setFinanceAmount(baseMapper.sumAmt(bo));
        return res;
    }

    /**
     * 查询客户财务台账列表
     */
    @Override
    public List<BillFinanceVo> queryList(BillFinanceBo bo) {
        LambdaQueryWrapper<BillFinance> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BillFinance> buildQueryWrapper(BillFinanceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BillFinance> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getHtName()), BillFinance::getHtName, bo.getHtName());
        lqw.orderByDesc(BillFinance::getPaymentDate);
        return lqw;
    }

    /**
     * 新增客户财务台账
     */
    @Override
    public Boolean insertByBo(BillFinanceBo bo) {
        BillFinance add = BeanUtil.toBean(bo, BillFinance.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
//        countsy(add);
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }
    public BillCustomInvest checkCustomInves(BillCustomInvest bo){
        if(bo.getUrif()==null){
            bo.setUrif(bo.getActualCash());

        }else{
            bo.setUrif(bo.getActualCash().add(bo.getActualCash()));
        }

        bo.setPnsoi(bo.getActualCash());
        return bo;
    }
    /**
     * 传入合同简称  查询客户台账，进行剩余备款计算
     */

    public void countsy(BillFinance bo){
        BillCustomInvestBo billCustomInvestBo = new BillCustomInvestBo();
        billCustomInvestBo.setHtName(bo.getHtName());

        BillCustomInvestVo billCustomInvestVo = new BillCustomInvestVo();
        //已做倒序
        List<BillCustomInvestVo> list = iBillCustomInvestService.queryList(billCustomInvestBo);
        if(!list.isEmpty()){
            //获取最新一条记录
            billCustomInvestVo = list.get(0);
            if(billCustomInvestVo.getBalance()!=null){
                billCustomInvestVo.setBalance(billCustomInvestVo.getBalance().add(bo.getAmount()));
            }else{
                // 第一条记录
                billCustomInvestVo.setBalance(bo.getAmount());
            }
        }else{
            //新录入 无处理
        }
        BillCustomInvestBo add = BeanUtil.toBean(billCustomInvestVo, BillCustomInvestBo.class);
        iBillCustomInvestService.updateByBo(add);
    }
    /**
     * 修改客户财务台账
     */
    @Override
    public Boolean updateByBo(BillFinanceBo bo) {
        BillFinance update = BeanUtil.toBean(bo, BillFinance.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BillFinance entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除客户财务台账
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
